<template>
	<view class="poster">
		
		<view class="poster-hd">
			<canvas canvas-id="CanvasID" :style="{ width: canvasW + 'px', height: canvasH + 'px' }" v-show="!showImg"></canvas>
			<image :src="imgUrl" :style="{ width: canvasW + 'px', height: canvasH + 'px' }" v-if="showImg"></image>
		</view>
		
		<view class="setting-btn">
			<view class="rest" @click="rest">重置</view>
			<view class="share" @click="set">设置推广语</view>
			<view class="custom" @click="custom">自定义封面</view>
		</view>
		
		<view class="poster-btn" v-if="!showImg">
			<view class="share" @click="share">保存</view>
		</view>
		
		<uni-popup type="bottom" ref="extendText">
			<view class="extendText">
				<input type="text" placeholder="请输入14个字内的推广语" v-model="extendtext" confirm-type="done" @confirm="confirmSet" maxlength="14" />
			</view>
		</uni-popup>
		
		<pt-openSetting ref="openSetting" tips="您已关闭相册访问开关，请打开开关后重新保存"></pt-openSetting>
		<pt-loading></pt-loading>
	</view>
</template>

<script>
	import md5 from '@/static/utils/md5.min.js'
	import store from 'store'
	export default {
		data() {
			return {
				imgSrc: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2021-03-25/20210325/0fb22649d1659b2c7eb473f057059cca.jpg',
				avatarBg: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2021-03-25/20210325/8c4a0dd8cf7c715ea67112faf1178bc8.png',
				wxIcon: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2021-03-25/20210325/3fa40af4e70db1fbc208ce76b2bb8b9e.png',
				heard_img: '',
				nickname: '',
				QrSrc: '',
				canvasW: 0,
				canvasH: 0,
				canvasImgSrc:'',
				ctx: null,
				Title: '家具大师',
				Referrer: '',
				ViewDetails: '扫码/长按识别二维码',
				restImg: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2021-03-25/20210325/0fb22649d1659b2c7eb473f057059cca.jpg',
				imgUrl: '',
				showImg: false,
				extendtext: '',
				role_type_name: '',
				uploadData: {
					timestamp: Math.round(new Date().getTime() / 1000),
					key: JSON.parse(uni.getStorageSync('userInfo')).token
				}
			};
		},
		onLoad(options) {
			this.getUserInfo()
			uni.$on('uAvatarCropper', path => {
				// #ifdef H5
				this.uploadData.port = 'h5'
				// #endif
				// #ifdef MP-WEIXIN
				this.uploadData.port = 'wechat'
				// #endif
				// #ifdef APP-PLUS
				switch(uni.getSystemInfoSync().platform){
					case 'android':
						this.uploadData.port = 'android'
					  break;
					case 'ios':
						this.uploadData.port = 'ios'
					  break;
				}
				// #endif
				
				let obj = 'jjds2020+'
				let newData = this.objKeySort(this.uploadData)
				for (let i in newData) {
					obj += i + '=' + newData[i] + '&'
				}
				obj = obj.substring(0, obj.length - 1)
				obj += '+jjds2020'
				obj = md5(obj)
				obj = obj.toUpperCase()
				this.uploadData.sign = obj
				// 可以在此上传到服务端
				uni.showLoading({
					title: '请稍后···'
				})
				uni.uploadFile({
					url: `${this.$domain}/api/Upimg/UpImg`,
					filePath: path,
					name: 'file',
					formData: this.uploadData,
					complete: (res) => {
						uni.hideLoading()
						this.imgSrc = JSON.parse(res.data).datas[0]
						this.$nextTick(() => {
							this.OnCanvas()
						})
					}
				})
			})
		},
		methods: {
			objKeySort(obj) {
				var newkey = Object.keys(obj).sort();
				var newObj = {};
				for (var i = 0; i < newkey.length; i++) {
					newObj[newkey[i]] = obj[newkey[i]];
				}
				return newObj;
			},
			getUserInfo(){
				uni.showLoading({
				    title: '加载中'
				});
				this.$u.apiWei.appCreateQr().then(qrRes => {
					uni.hideLoading();
					this.QrSrc = qrRes.datas
				}).then(qrRes => {
					this.$u.apiWei.UserInfo().then(res => {
						this.Title = res.datas.nickname
						this.Referrer = res.datas.phone
						this.heard_img = res.datas.heard_img
						this.nickname = res.datas.nickname
						switch (res.datas.role_type){
							case 1:
								this.role_type_name = '普通用户'
								break;
							case 2:
								this.role_type_name = '商户'
								break;
							case 3:
								this.role_type_name = '分销员'
								break;
							case 4:
								this.role_type_name = '导购员/代理商'
								break;
							case 6:
								this.role_type_name = '业绩'
								break;
							case 7:
								this.role_type_name = '招商'
								break;
							case 8:
								this.role_type_name = '工厂'
								break;
							case 9:
								this.role_type_name = '仓库'
								break;
							case 10:
								this.role_type_name = '外部工厂'
								break;
							case 11:
								this.role_type_name = '商家财务'
								break;
							case 12:
								this.role_type_name = '工厂客服'
								break;
							case 14:
								this.role_type_name = '设计师'
								break;
						}
						if(res.datas.extend_text){
							this.ViewDetails = res.datas.extend_text
						}
						this.OnCanvas();
					})
				})
			},
			async OnCanvas() {
				let _this = this;
				_this.ctx = uni.createCanvasContext('CanvasID');
				const systemInfo = uni.getSystemInfoSync()
				const _imgInfo = await _this.getImageInfo({ imgSrc: _this.imgSrc }); // 背景图
				const _QrCode = await _this.getImageInfo({ imgSrc: _this.QrSrc }); //二维码
				const _avatarBg = await _this.getImageInfo({ imgSrc: _this.avatarBg }); //头像背景
				const _wxIcon = await _this.getImageInfo({ imgSrc: _this.wxIcon }); // 微信icon
				const _avatar = await _this.getImageInfo({ imgSrc: _this.heard_img }); // 微信头像
				_this.canvasW = uni.upx2px(612)
				_this.canvasH = uni.upx2px(990)
				
				_this.ctx.setFillStyle('#FFFFFF');
				_this.ctx.fillRect(0,0,_this.canvasW,_this.canvasH)
				
				//添加背景图
				_this.ctx.drawImage(_imgInfo.path, 0, 0, uni.upx2px(612), uni.upx2px(702));
				//添加背景图 end
				
				//添加头像背景图
				_this.ctx.drawImage(_avatarBg.path, uni.upx2px(30), uni.upx2px(639), uni.upx2px(170), uni.upx2px(65));
				//添加头像背景图 end
				
				// 微信icon
				_this.ctx.drawImage(_wxIcon.path, uni.upx2px(54), uni.upx2px(843), uni.upx2px(33), uni.upx2px(28));
				//微信icon end
				
				//添加二维码
				_this.ctx.drawImage(_QrCode.path, uni.upx2px(424), uni.upx2px(774), uni.upx2px(172), uni.upx2px(172));
				//添加二维码 end
				
				//添加头像
				_this.ctx.save()
				_this.ctx.beginPath()
				_this.ctx.arc(uni.upx2px(116), uni.upx2px(706), uni.upx2px(53), 0, Math.PI * 2, false);
				_this.ctx.fill()
				_this.ctx.clip()
				_this.ctx.drawImage(_avatar.path, uni.upx2px(65), uni.upx2px(652), uni.upx2px(106), uni.upx2px(106));
				_this.ctx.restore()
				//添加头像 end
				
				// 昵称
				let nickname
				if(_this.nickname.length > 11){
					nickname = _this.nickname.substring(0,10)+'...'
				}else{
					nickname = _this.nickname
				}
				_this.ctx.setFillStyle('#444');
				_this.ctx.font = 'bold nomal 16px Arial';
				_this.ctx.fillText(nickname, uni.upx2px(54) , uni.upx2px(810));
				// 昵称 end
				
				// 用户身份
				const role_type_name = _this.role_type_name
				_this.ctx.setFillStyle('#F59359');
				_this.ctx.font = 'nomal nomal 11px Arial';
				if(_this.nickname.length > 11){
					_this.ctx.fillText(role_type_name, _this.ctx.measureText(nickname).width + uni.upx2px(196), uni.upx2px(806));
				}else if(_this.nickname.length > 5){
					_this.ctx.fillText(role_type_name, _this.ctx.measureText(nickname).width + uni.upx2px(160), uni.upx2px(806));
				}else{
					_this.ctx.fillText(role_type_name, _this.ctx.measureText(nickname).width + uni.upx2px(116), uni.upx2px(806));
				}
				// 用户身份 end
				
				// 身份边框背景
				_this.ctx.save()
				_this.ctx.beginPath()
				let w = _this.ctx.measureText(role_type_name).width + 15
				_this.ctx.setStrokeStyle('#F59359')
				if(_this.nickname.length > 11){
					_this.ctx.strokeRect(_this.ctx.measureText(nickname).width + uni.upx2px(180), uni.upx2px(780), w, uni.upx2px(36));
				}else if(_this.nickname.length > 5){
					_this.ctx.strokeRect(_this.ctx.measureText(nickname).width + uni.upx2px(150), uni.upx2px(780), w, uni.upx2px(36));
				}else{
					_this.ctx.strokeRect(_this.ctx.measureText(nickname).width + uni.upx2px(105), uni.upx2px(780), w, uni.upx2px(36));
				}
				_this.ctx.stroke();
				// 身份边框背景
				
				// 微信号
				const wechatName = '微信号：'+ _this.Referrer
				_this.ctx.setFillStyle('#444');
				_this.ctx.font = 'normal nomal 13px Arial';
				_this.ctx.fillText(wechatName, uni.upx2px(100) , uni.upx2px(865));
				// 微信号 end
				
				// 推广语
				const ViewDetails = _this.ViewDetails
				_this.ctx.setFillStyle('#F59359');
				_this.ctx.font = 'normal nomal 14px Arial';
				_this.ctx.fillText(ViewDetails, uni.upx2px(54) , uni.upx2px(930));
				// 微信号 end
				
				//延迟后渲染至canvas上
				setTimeout(function() {
					_this.ctx.draw(false,(e) => {
						_this.createdImg()
					});
				}, 600);
			},
			async roundRectColor(context, x, y, w, h, r) {  //绘制圆角矩形（纯色填充）
			  context.save();
			  context.setFillStyle("#000");
			  context.setStrokeStyle('#000')
			  context.setLineJoin('round');  //交点设置成圆角
			  context.setLineWidth(r);
			  context.strokeRect(x + r/2, y + r/2, w - r , h - r );
			  context.fillRect(x + r, y + r, w - r * 2, h - r * 2);
			  context.stroke();
			  context.closePath();
			},
			async getImageInfo({ imgSrc }) {
				uni.showLoading({
					title: '正在生成海报',
					mask: true
				})
				return new Promise((resolve, errs) => {
					if(imgSrc.indexOf('https')!=-1){
						uni.downloadFile({
							url: imgSrc,
							success:function(res){
								uni.getImageInfo({
									src: res.tempFilePath,
									success: function(image) {
										uni.hideLoading()
										resolve(image);
									},
									fail(err) {
										uni.hideLoading()
										uni.showToast({
											title: '生成失败，请退出重试',
											icon: 'none',
											duration: 1500
										})
										errs(err);
									}
								});
							}
						})
					}else{
						uni.getImageInfo({
							src: imgSrc,
							success: function(image) {
								uni.hideLoading()
								resolve(image);
							},
							fail(err) {
								uni.hideLoading()
								uni.showToast({
									title: '生成失败，请退出重试',
									icon: 'none',
									duration: 1500
								})
								errs(err);
							}
						});
					}
				});
			},
			// 自定义选择图片
			custom(){
				this.$u.route({
					// 关于此路径，请见下方"注意事项"
					url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
					// 内部已设置以下默认参数值，可不传这些参数
					params: {
						// 输出图片宽度，高等于宽，单位px
						destWidth: 612,
						destHeight: 702,
						// 裁剪框宽度，高等于宽，单位px
						rectWidth: uni.upx2px(612),
						rectHeight: uni.upx2px(702),
						// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
						fileType: 'png',
					}
				})
			},
			// 重置
			rest(){
				this.imgSrc = this.restImg
				this.OnCanvas();
			},
			// 保存图片到相册
			saveImg(){
				uni.showModal({
					content: '保存海报后即可从相册分享或发送给朋友，是否保存?',
					confirmText: '是',
					cancelText: '否',
					success: (res) => {
						if(res.confirm){
							uni.showLoading({
								title: '正在保存',
								mask: true
							})
							uni.canvasToTempFilePath({
							  canvasId: 'CanvasID',
								width: uni.upx2px(612),
								height: uni.upx2px(990),
								destWidth: 612,
								destHeight: 990,
								success: (data) => {
									uni.hideLoading()
									// #ifdef MP-WEIXIN
									uni.getSetting({
										withSubscriptions: true,
										success: (scope) => {
											if(!scope.authSetting['scope.writePhotosAlbum']){
												uni.authorize({
													scope: 'scope.writePhotosAlbum',
													success: () => {
														uni.saveImageToPhotosAlbum({
															filePath: data.tempFilePath,
															success(saveRes) {
																uni.showToast({
																	icon: 'none',
																	title: '保存成功，请在相册中查看',
																	duration: 1500
																})
															},
															fail: () => {
																uni.showToast({
																	icon: 'none',
																	title: '保存失败，您已取消保存图片'
																})
															}
														})
													},
													fail: () => {
														// uni.showToast({
														// 	icon: 'none',
														// 	title: '您已关闭相册访问开关，请开启后重新保存'
														// })
														this.$refs.openSetting.init()
													}
												})
											}else{
												uni.saveImageToPhotosAlbum({
													filePath: data.tempFilePath,
													success(saveRes) {
														uni.showToast({
															icon: 'none',
															title: '保存成功，请在相册中查看',
															duration: 1500
														})
													},
													fail: () => {
														uni.showToast({
															icon: 'none',
															title: '保存失败，您已取消保存图片'
														})
													}
												})
											}
										}
									})
									// #endif
									// #ifdef APP-PLUS || H5
									uni.saveImageToPhotosAlbum({
										filePath: data.tempFilePath,
										success(saveRes) {
											uni.showToast({
												icon: 'none',
												title: '保存成功，请在相册中查看',
												duration: 1500
											})
										},
										fail: () => {
											uni.showToast({
												icon: 'none',
												title: '保存失败，您已取消保存图片'
											})
										}
									})
									// #endif
								}
							})
						}
					}
				})
			},
			// 生成img
			createdImg(){
				let _this = this
				uni.canvasToTempFilePath({
				  destWidth: 600,
				  destHeight: 1070,
				  canvasId: 'CanvasID',
				  success: function(data) {
						_this.imgUrl = data.tempFilePath
				  }
				})
			},
			showOrhide(e){
				this.showImg = e.show
				if(!e.show){
					this.OnCanvas()
				}
			},
			// 分享保存
			save(){
				this.saveImg()
			},
			// 分享操作
			share(){
				let _this = this
				this.saveImg()
			},
			// 点击分享
			shareBtn(e){
				if(e!=3){
					let scene = ''
					if(e==1){
						scene = 'WXSceneSession'
					}else if(e==2){
						scene = 'WXSenceTimeline'
					}
					let img = '';
					uni.showLoading({
						title: '正在生成··',
						mask: true
					})
					uni.canvasToTempFilePath({
					  destWidth: 600,
					  destHeight: 1070,
					  canvasId: 'CanvasID',
					  success: function(data) {
							uni.hideLoading()
							img = data.tempFilePath
							uni.share({
								provider: "weixin",
								scene: scene,
								type: 2,
								imageUrl: img,
								success: function (res) {
									console.log("success:" + JSON.stringify(res));
								},
								fail: function (err) {
									console.log("fail:" + JSON.stringify(err));
								}
							});
					  }
					})
				}else{
					let img = '';
					uni.showLoading({
						title: '正在生成··',
						mask: true
					})
					uni.canvasToTempFilePath({
					  destWidth: 600,
					  destHeight: 1070,
					  canvasId: 'CanvasID',
					  success: function(data) {
							uni.hideLoading()
							img = data.tempFilePath
							uni.share({
								provider: 'sinaweibo',
								type: 2,
								imageUrl: img,
								success: function (res) {
									console.log("success:" + JSON.stringify(res));
								},
								fail: function (err) {
									console.log("fail:" + JSON.stringify(err));
								}
							});
					  }
					})
				}
			},
			set(){
				this.$refs.extendText.open()
			},
			confirmSet(e){
				if(!e.detail.value){
					return uni.showToast({
						icon: 'none',
						title: '不能为空'
					})
				}
				this.$u.api.SetExtendText({extend_text: e.detail.value}).then(res => {
					this.ViewDetails = e.detail.value
					this.OnCanvas();
					this.$refs.extendText.close()
				})
			}
		},
		mounted() {
			
		}
	}
</script>

<style lang="scss">
	.poster{
		padding-top: 20rpx;
		padding-bottom: 190rpx;
		canvas,image{
			background-color: #FFF;
			display: block;
			margin: 0 auto;
			box-shadow: 0px 0 16rpx 0px rgba(0, 0, 0, 0.24);
			border-radius: 8rpx;
		}
		.setting-btn{
			margin-top: 70rpx;
			display: flex;
			justify-content: center;
			view{
				line-height: 60rpx;
				width: 200rpx;
				text-align: center;
				border-radius: 30rpx;
				border: 1px solid #E6E6E6;
				font-size: 28rpx;
				color: #333;
				&.share{
					width: 200rpx;
					margin: 0 30rpx;
				}
			}
		}
		.poster-btn{
			position: fixed;
			height: 120rpx;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #FFF;
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 10;
			padding: 0 75rpx;
			border-top: solid 1px #EEE;
			view{
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 8rpx;
				font-size: 28rpx;
				&.share{
					text-align: center;
					flex: 1;
					background-color: #FE9B26;
					color: #FFF;
				}
			}
			.share{
				background-color: #F59359;
				color: #fff;
			}
			.custom{
				background-color: #141414;
				color: #fff;
			}
		}
		.share-pop{
			background-color: #FFF;
			padding: 40rpx 0;
			.share-pop-tit{
				text-align: center;
				margin-bottom: 40rpx;
			}
			.share-pop-list{
				display: flex;
				.share-pop-list-item{
					flex: 1;
					text-align: center;
					image{
						width: 80rpx;
						height: 80rpx;
						vertical-align: top;
					}
					text{
						font-size: 24rpx;
						display: block;
						margin-top: 20rpx;
					}
				}
			}
			.share-save{
				margin-top: 40rpx;
				padding: 0 80rpx;
				button{
					border-radius: 100rpx;
					height: 80rpx;
					line-height: 80rpx;
				}
			}
		}
		.extendText{
			background-color: #FFF;
			border-radius: 10rpx 10rpx 0 0;
			padding: 30rpx;
			input{
				border: solid 1px #EEE;
				font-size: 24rpx;
				height: 80rpx;
				padding: 0 10rpx;
			}
		}
	}
</style>